<template>
    <div class="is2048Content">
        <div class="top">
			<div class="score">
				<p>得分: <span>{{total}}</span></p>
			</div>
			<div class="time">
				<p>用时: <span>{{allTime}}</span> 秒</p>
			</div>
		</div>
		<div class="center">
			<div class="mainBox">
				<div class="row" v-for="(row, rowIndex) in gameBoard" :key="rowIndex">
					<div class="cell" v-for="(cell, cellIndex) in row" :key="cellIndex">
						<div :class="cellIndex==newArr[0][1]&&rowIndex==newArr[0][0]||cellIndex==newArr[1][1]&&rowIndex==newArr[1][0]?'newBox':cell!==0?'cellBox':''">
							<div class="colorBox"
								:style="{backgroundColor:cell==2?'#eae0c9':cell==4?'#eae0c9':cell==8?'#ff9b29':cell==16?'#ff3a3a':cell==32?'#369083':cell==64?'#2e3cff':cell==128?'#c12fff':cell==256?'#ff77ed':cell==512?'#ffe9fe':cell==1024?'#fffcd4':cell==2048?'#04010b':''}">
								<text v-show="cell!==0&&cell!==1">{{ cell }}</text>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="bottom">
			<div class="jinxing" v-if="gameStatus">
				<div class="flexBox">
                    <div class="gameOverBtn">
                        <van-button style="width: 90%;background: #15256a;color: #FFF;border-radius: 16px;border: none; transition: all 0.3s ease;"
                        @click="gameOver">结束</van-button>
                    </div>
					<div class="contorl">
                        <div class="zuo" @click="zuo()">
                            <SvgIcon width="120px" height="120px" name="left" color="#808080"></SvgIcon>
                        </div>
                        <div class="zhong">
                            <div class="shang" @click="shang()">
                                <SvgIcon width="100px" height="100px" name="up" color="#808080"></SvgIcon>
                            </div>
                            <div class="xia" @click="xia()">
                                <SvgIcon width="100px" height="100px" name="down" color="#808080"></SvgIcon>
                            </div>
                        </div>
                        <div class="you" @click="you()">
                            <SvgIcon width="120px" height="120px" name="right" color="#808080"></SvgIcon>
                        </div>
					</div>
				</div>
			</div>
            <div class="kaishi" v-else>
				<div class="flexBox">
                    <van-button style="width: 90%;background: #15256a;color: #FFF;border-radius: 16px;border: none; transition: all 0.3s ease;"
                    @click="gameStart">游戏开始</van-button>
                </div>
			</div>
		</div>
    </div>
</template>
    
<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showFailToast, showConfirmDialog } from 'vant'


const route = useRoute()
const router = useRouter()


// 游戏状态
const gameStatus = ref<boolean>(false);
// 显示的数组
let gameBoard = ref<number[][]>(Array.from({ length: 4 }, () => Array(4).fill(0)));
// 新增的俩
let newArr = ref<number[][]>(Array.from({ length: 2 }, () => Array(2).fill(null)))
// 得分
const total = ref<number>(0)
// 用时
const allTime = ref<number>(0)
const timer1 = ref<any>(null)
// 游戏开始
const gameStart = () => {
    total.value = 0;
    allTime.value = 0
    gameStatus.value = true;
    gameBoard.value = numInit()
    timer1.value = setInterval(() => {
        allTime.value = allTime.value + 1;
    }, 1000)
}
// 游戏结束
const gameOver = () => {
    gameStatus.value = false;
    clearInterval(timer1.value)
    timer1.value = null;
    newArr.value = Array.from({ length: 2 }, () => Array(2).fill(null));
    showConfirmDialog({
        title: '温馨提示',
        confirmButtonColor: '#bca1f3',
        message: '游戏结束，要重新开始吗？',
    })
    .then(() => {
        gameStart()
    })
    .catch(() => {
        // on cancel
        router.go(-1)
    });
}
// 获取随机数的函数
const getRandomlet = (min: any, max: any) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 随机初始化数值
const numInit = () => {
    const array = Array.from({ length: 4 }, () => Array(4).fill(0));
    const positions: any = [];
    // 生成一个包含所有可能位置的数组  
    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
            positions.push({ x: i, y: j });
        }
    }
    // 随机选择6个位置  
    const selectedPositions: any = [];
    for (let i = 0; i < 6; i++) {
        const randomIndex = getRandomlet(0, positions.length - 1);
        selectedPositions.push(positions[randomIndex]);
        positions.splice(randomIndex, 1); // 从数组中移除已选位置，避免重复选择  
    }
    // 设置前4个位置为2  
    for (let i = 0; i < 4; i++) {
        const position = selectedPositions[i];
        array[position.x][position.y] = 2;
    }
    // 对于剩下的2个位置，随机设置为4或8  
    for (let i = 4; i < 6; i++) {
        const position = selectedPositions[i];
        const randomValue = getRandomlet(1, 2) === 1 ? 4 : 8;
        array[position.x][position.y] = randomValue;
    }
    return array;
}
// 旋转数组
const rotate90Clockwise = (matrix: any) => {
    const n = matrix.length;
    let rotatedMatrix: any = Array.from({ length: n }, () => []);

    // 顺时针旋转90度
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            rotatedMatrix[j][n - i - 1] = matrix[i][j];
        }
    }

    return rotatedMatrix;
}
// 累计与填入
const addNum = (arr: any) => {
    let copiedArray = JSON.parse(JSON.stringify(arr));
    let defen = 0;
    for (let i = 0; i < copiedArray.length; i++) {
        for (let j = 0; j < copiedArray[i].length; j++) {
            // 找到第一个不为0
            if (copiedArray[i][j] !== 0) {
                for (let p = 0; p < j; p++) {
                    if (copiedArray[i][p] == copiedArray[i][j]) {
                        copiedArray[i][p] = copiedArray[i][j] + copiedArray[i][p];
                        defen = defen + copiedArray[i][p] / 2;
                        copiedArray[i][j] = 0;
                    }
                    // 移动到第一个0
                    if (copiedArray[i][p] == 0) {
                        copiedArray[i][p] = copiedArray[i][j];
                        copiedArray[i][j] = 0;
                    }
                }
            }
        }
    }
    if (total.value) {
        total.value = total.value + defen
    }
    return copiedArray;
}
// 添加新数字
const addRandomNumbersToZeros = (arr: any) => {
    let matrix = JSON.parse(JSON.stringify(arr));
    // 存储所有值为0的元素的坐标  
    let zeroIndices: any = [];
    // 遍历二维数组，找到值为0的元素的坐标  
    for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < matrix[i].length; j++) {
            if (matrix[i][j] === 0) {
                zeroIndices.push([i, j]);
            }
        }
    }
    // 如果没有0，则无法添加数字  
    if (zeroIndices.length < 2) {
        gameOver()
        return;
    }
    // 从所有0的坐标中随机选择两个  
    let randomIndices = zeroIndices.sort(() => 0.5 - Math.random()).slice(0, 2);
    // 为这两个坐标对应的元素添加随机数字  
    let randomNumbers = [2, 4, 8];
    for (let index of randomIndices) {
        let [row, col] = index as any;
        let randomNumber = randomNumbers[Math.floor(Math.random() * randomNumbers.length)];
        matrix[row][col] = randomNumber;
    }
    newArr.value = randomIndices;
    return matrix;
}
// 移动
const moveAndMerge = (dir) => {
    if (dir == 'shang') {
        gameBoard.value = addNum(gameBoard.value)
    }
    else if (dir == 'zuo') {
        let newArr = JSON.parse(JSON.stringify(gameBoard.value));
        newArr = rotate90Clockwise(addNum(rotate90Clockwise(rotate90Clockwise(rotate90Clockwise(newArr)))))
        gameBoard.value = newArr
    } else if (dir == 'you') {
        let newArr = JSON.parse(JSON.stringify(gameBoard.value));
        newArr = rotate90Clockwise(rotate90Clockwise(rotate90Clockwise(addNum(rotate90Clockwise(newArr)))))
        gameBoard.value = newArr
    } else if (dir == 'xia') {
        let newArr = JSON.parse(JSON.stringify(gameBoard.value));
        newArr = rotate90Clockwise(rotate90Clockwise(addNum(rotate90Clockwise(rotate90Clockwise(newArr)))))
        gameBoard.value = newArr
    }
    gameBoard.value = addRandomNumbersToZeros(gameBoard.value)
}
// 操作
const shang = () => {
    moveAndMerge('shang')
}
const xia = () => {
    moveAndMerge('xia')
}
const zuo = () => {
    moveAndMerge('zuo')
}
const you = () => {
    moveAndMerge('you')
}

onMounted(() => {

})

onUnmounted(() => {

})

</script>


<style lang="scss" scoped>
.is2048Content {
    width: 100%;
    height: auto;
    min-height: 100vh;
    position: relative;
    // padding: 15px;
    overflow: hidden;
    // background-color: #c6ffe6;
    display: flex;
    flex-direction: column;
    font-family: cuteFont;
    .top {
        width: 100%;
        height: auto;
        min-height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        .score {
            margin-right: 30px;
            p {
                font-size: 16px;
                font-weight: 500;
                span {
                    font-size: 22px;
                    font-weight: 700;
                    color: #9d6fff;
                }
            }
        }
        .time {
            p {
                font-size: 16px;
                font-weight: 500;
                span {
                    font-size: 22px;
                    font-weight: 700;
                    color: #9d6fff;
                }
            }
        }
    }
    .center {
        width: 100vw;
        height: 100vw;
        .mainBox {
            width: 90%;
            margin: 5% 5%;
            height: 90%;
            border-radius: 18px;
            border: 5px solid #b9aea2;
            display: flex;
            .row {
                flex: 1;
                display: flex;
                flex-direction: column;
            }
            .cell {
                flex: 1;
                border: 5px solid #b9aea2;
                background-color: #cbc1b6;
                display: flex;
                justify-content: center;
                align-items: center;
                color: #ffffff;
                font-size: 14px;
                .newBox {
                    width: 90%;
                    height: 90%;
                    background-color: #9d6fff;
                    border-radius: 15px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    animation: newBox 0.5s;
                }
                .cellBox {
                    width: 90%;
                    height: 90%;
                    background-color: #9d6fff;
                    border-radius: 15px;
                }
                .colorBox {
                    width: 100%;
                    border-radius: 15px;
                    height: 100%;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    color: #999;
                    font-size: 20px;
                    font-weight: 700;
                }
            }
        }
    }
    .bottom {
        flex: 1;
        position: relative;
        .kaishi {
            width: 100%;
            height: auto;
            min-height: 50px;
            margin-top: 30px;
            position: absolute;
            .flexBox {
                width: inherit;
                height: inherit;
                display: flex;
                justify-content: center;
                align-items: center;
            }
        }
        .jinxing {
            width: 100%;
            height: auto;
            min-height: 100%;
            .flexBox {
                width: inherit;
                height: inherit;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                .gameOverBtn {
                    width: 100%;
                    height: auto;
                    text-align: center;
                }
                .contorl {
                    margin-top: 15px;
                    width: 100%;
                    height: auto;
                    min-height: 80px;
                    display: flex;
                    flex-direction: row;
                    justify-content: center;
                    align-items: center;
                    .zuo {
                        flex: 1;
                        width: 100%;
                        height: 100%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }
                    .you {
                        flex: 1;
                        width: 100%;
                        height: 100%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }
                    .zhong {
                        flex: 1;
                        width: 100%;
                        height: 100%;
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;
                        .shang {
                            width: 100%;
                            height: 100%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            margin-bottom: 10px;
                        }
                        .xia {
                            width: 100%;
                            height: 100%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                        }
                    }
                    // clip-path: polygon(0% 20%, 50% 20%, 50% 0%, 100% 50%, 50% 100%, 50% 80%, 0% 80%);
                }
            }
        }
    }
}
@keyframes newBox {
    0% {
        width: 0%;
        height: 0%;
    }
    100% {
        width: 90%;
        height: 90%;
    }
}
</style>